package utils

import (
	"encoding/json"
	"github.com/flipped-aurora/gin-vue-admin/server/model/entity/video"
	"log"
	"reflect"
)

func handel(tree *video.XkVideoCategory, v video.XkVideoCategory) {
	if v.ParentId == 0 {
		//v.TopObj = &video.XkVideoCategory{
		//	CategoryName: tree.CategoryName,
		//}
		tree.Children = append(tree.Children, &v)
	} else {
		if len(tree.Children) > 0 {
			for key, value := range tree.Children {
				if value.ID == v.ParentId {
					//v.TopObj = &video.XkVideoCategory{
					//	CategoryName: value.CategoryName,
					//}
					tree.Children[key].Children = append(tree.Children[key].Children, &v)
				} else {
					handel(tree.Children[key], v)
				}
			}
		}
	}
}

func CallbackFunc(a []video.XkVideoCategory) map[string]any {
	root := &video.XkVideoCategory{
		ID:           0,
		CategoryName: "/",
	}
	for _, v := range a {
		handel(root, v)
	}

	jsonStr, err := json.MarshalIndent(root, " ", "\t")
	if err != nil {
		log.Fatalln(err)
	}

	var m map[string]any
	json.Unmarshal(jsonStr, &m)

	return m
}

// 生成树结构
func tree(menus []*video.XkVideoCategory, parentId uint) []*video.XkVideoCategory {
	//定义子节点目录
	var nodes []*video.XkVideoCategory
	if reflect.ValueOf(menus).IsValid() {
		//循环所有一级菜单
		for _, v := range menus {
			//查询所有该菜单下的所有子菜单
			if v.ParentId == parentId {
				//特别注意压入元素不是单个所有加三个 **...** 告诉切片无论多少元素一并压入
				v.Children = append(v.Children, tree(menus, v.ID)...)
				nodes = append(nodes, v)
			}

		}
	}
	return nodes
}
